<template>
  <div class="manage">
    <div class="manage-header">
      <!-- 新增按钮 -->
      <el-button type="primary" @click="handlecreate">+ 新增</el-button>

      <!-- 对话框:点击新增或编辑才会弹出表单 -->
      <!-- :before-close="closeDialog" 点击关闭的x之前要做的事情 -->
      <el-dialog
        :title="modalType == 0 ? '新建' : '编辑'"
        :visible.sync="dialogVisible"
        width="450px"
        :before-close="closeDialog"
      >
        <!-- 表单Form -->
        <!-- ref=form:为了通过this.$refs调用组件的方法 -->
        <el-form :inline="true" :model="form" ref="form">
          <!-- 每一项表单域:el-form-item -->
          <el-form-item label="姓名" prop="name">
            <el-input placeholder="请输入姓名" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="年龄" prop="name">
            <el-input placeholder="输入年龄" v-model="form.age"></el-input>
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请输入性别">
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="电话号码" prop="phoneNumber">
            <el-input
              placeholder="请输入电话号码"
              v-model="form.phoneNumber"
            ></el-input>
          </el-form-item>

          <div>
            <span>上传图片</span>
            <el-upload
              class="avatar-uploader"
              action="http://localhost:11143/common/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              clearable
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 搜索框 -->
      <el-form :inline="true">
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="common-table">
      <!-- 用户数据Table -->
      <el-table :data="tableData" stripe style="width: 100%" height="90%">
        <el-table-column prop="name" label="姓名"> </el-table-column>
        <el-table-column prop="age" label="年龄"> </el-table-column>
        <el-table-column prop="avatar" label="照片">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" width="80" />
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别">
          <template slot-scope="scope">
            <span>{{ scope.row.gender == 1 ? "男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="等级">
          <template slot-scope="scope">
            <span>{{ scope.row.permissionLevel == 1 ? "管理员" : "店员" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              @change="handleStatusChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="phoneNumber" label="电话号码"> </el-table-column>
        <!-- 自定义列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="warning" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pager">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          @current-change="currentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import http from "@/utils/request";
export default {
  data() {
    return {
      imageUrl: "",
      // 表单绑定的数据
      form: {
        avatar: "",
        name: "",
        gender: "",
        phoneNumber: "",
        status: "0",
        permissionLevel: "0",
      },
      // 表单验证规则
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        gender: [{ required: true, message: "请输入性别", trigger: "blur" }],
        phoneNumber: [
          { required: true, message: "请输入电话号", trigger: "blur" },
        ],
      },
      // 表单是否打开
      dialogVisible: false,
      // 列表数据
      temp: "",
      tableData: [],
      // 打开表单:新建0,编辑1
      modalType: 0,
      // 分页的对象
      pageData: {
        page: 1,
        limit: 10,
      },
      // 分页页数
      total: 0,
      // 搜索框表单
      searchForm: {
        name: "",
      },
    };
  },
  methods: {
    handleStatusChange(data) {
      console.log("查看数据", data);
      http.put(`/user/update`, data).then(({ data }) => {
        if (data.code == 1) {
          this.$message({
            type: "success",
            message: "状态修改!",
          });
          this.getList();
          this.closeDialog();
        } else {
          this.$message.error("修改失败!");
        }
      });
    },
    // 获取列表数据
    getList() {
      // 由接口文档知传入一个对象:要返回的是当前页面数据和搜索到的数据的交集
      http
        .get(
          `user/list?page=${this.pageData.page}&limit=${this.pageData.limit}`
        )
        .then(({ data }) => {
          this.tableData = data.data.records;
          console.info("表单数据", this.tableData);
          this.total = data.data.title || 0;
        });
    },
    // 表单提交
    submit() {
      this.form.avatar = this.imageUrl;
      if (this.modalType == 0) {
        http.post(`/user/save`, this.form).then(({ data }) => {
          if (data.code == 1) {

            this.getList();
            this.closeDialog();
            this.$message({
              showClose: true,
              type:"success",
              message: ('该用户的id为'+data.data),
              duration:0
            });
          } else {
            this.$message.error("保存失败!");
          }
        });
      } else {
        http.put(`/user/update`, this.form).then(({ data }) => {
          if (data.code == 1) {
            this.$message({
              type: "success",
              message: "已编辑!",
            });
            this.getList();
            this.closeDialog();
          } else {
            this.$message.error("编辑失败!");
          }
        });
      }
    },

    closeDialog() {
      (this.form = {
        avatar: "",
        name: "",
        gender: "",
        age: "",
        phoneNumber: "",
        status: "0",
        permissionLevel: "0",
      }),
        (this.dialogVisible = false);
    },
    // 编辑按钮
    handleEdit(index) {
      this.modalType = 1;
      this.openForm();
      // 深拷贝yarn
      this.form = JSON.parse(JSON.stringify(index));
    },
    // 删除按钮
    handleDelete(index) {
      this.$confirm("此操作将永久删除该员工, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除操作:根据后端接口,参数是对象,id是唯一标识符
          http.delete(`/user/delete/${index.id}`).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
          });
        })
        .catch(() => {
          // 点击取消:不删除了
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleAvatarSuccess(res, file) {
      console.log("返回的链接是", res.data);
      this.imageUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
    },

    // 新建按钮
    handlecreate() {
      this.modalType = 0;
      this.openForm();
    },
    // 打开表单
    openForm() {
      this.dialogVisible = true;
    },
    // 改变页码
    currentChange(val) {
      this.pageData.page = val;
      this.getList();
    },
    // 搜索
    search() {
      this.getList();
    },
  },
  mounted() {
    this.getList();
  },
};
</script>

<style lang="less" scoped>
.manage {
  height: 100%;

  .manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .common-table {
    height: 90%;
    position: relative;

    .pager {
      position: absolute;
      right: 20px;
      bottom: 0;
    }
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
